package com.bullsora.kindlerss.web.mvc;

import com.bullsora.kindlerss.model.AppUser;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.TimeZone;

@RequestMapping("/appusers")
@Controller
@RooWebScaffold(path = "appusers", formBackingObject = AppUser.class)
public class AppUserController {

  public static final List<String> AVAILABLE_TIMEZONES = Arrays.asList(TimeZone.getAvailableIDs());

  static {
    Collections.sort(AVAILABLE_TIMEZONES);
  }
  

  @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
  public String update(@Validated({AppUser.PasswordInput.class}) AppUser appUser, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
    if (bindingResult.hasErrors()) {
      populateEditForm(uiModel, appUser);
      return "appusers/update";
    }
    uiModel.asMap().clear();
    appUserService.updateAppUser(appUser);
    return "redirect:/appusers/" + encodeUrlPathSegment(appUser.getId().toString(), httpServletRequest);
  }

  @RequestMapping(method = RequestMethod.POST, produces = "text/html")
  public String create(@Validated({AppUser.PasswordInput.class}) AppUser appUser, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
    if (bindingResult.hasErrors()) {
      populateEditForm(uiModel, appUser);
      return "appusers/create";
    }
    uiModel.asMap().clear();
    appUserService.saveAppUser(appUser);
    return "redirect:/appusers/" + encodeUrlPathSegment(appUser.getId().toString(), httpServletRequest);
  }

  void populateEditForm(Model uiModel, AppUser appUser) {
    uiModel.addAttribute("appUser", appUser);
    uiModel.addAttribute("timezones", AVAILABLE_TIMEZONES);
  }

}
